package com.peng.leetcode.tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * PreorderTraversal
 * <p>
 * Created on 2022/11/29
 *
 * @author lupeng
 */
public class PreorderTraversal {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        ArrayDeque<TreeNode> q = new ArrayDeque<>();
        while (root != null || !q.isEmpty()) {
            while (root != null) {
                ans.add(root.val);
                q.offer(root);
                root = root.left;
            }
            root = q.pollLast();
            root = root.right;
        }
        return ans;
    }
}
